package com.andy.qhb.controller.game;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.andy.qhb.base.RespVO;
import com.andy.qhb.controller.GameController;
import com.andy.qhb.dao.DaoUtils;
import com.andy.qhb.entity.UsrGroups;
import com.andy.qhb.entity.UsrUser;
import com.andy.qhb.game.GameUser;
import com.andy.qhb.game.Global;
import com.andy.qhb.game.GlobalHttp;
import com.andy.qhb.utils.JsonUtils;
import com.andy.qhb.vo.HFriend;

@Controller
@RequestMapping(value="game/api")
public class Api114Controller extends GameController{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	/**
	 * 邀请入群
	 * @param session
	 * @param data
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="114")
	public RespVO action(HttpSession session,String data) throws Exception{
		GameUser user = getUser(session);
		Map<String, Object> reqData = JsonUtils.json2Map(data);
		
		Long groupId = MapUtils.getLong(reqData,"gid");
		String userIds = MapUtils.getString(reqData,"uids");
		
		UsrGroups usrGroup = Global.getUsrGroup(groupId);
		if(StringUtils.isBlank(userIds)){
			return RespVO.createErrorJsonResonse("请选择玩家");
		}
		if(usrGroup == null || !usrGroup.getCid().equals(user.getId())) {
			return RespVO.createErrorJsonResonse("error114");
		}
		
		for(String userId:userIds.split(",")){
			UsrUser usrUser = DaoUtils.getOneSql(UsrUser.class, "select id,nick_name,icon from usr_user where id=?", userId);
			if(usrUser == null) {
				continue;
			}
			if(usrGroup.addMember(usrUser.getId(), usrUser.getNickName(),usrUser.getIcon())){
				DaoUtils.update(usrGroup);
				GameUser tarUser = GlobalHttp.getUser(usrUser.getId());
				if(tarUser != null) {
					tarUser.getGroups().add(new HFriend(groupId, usrGroup.getName(),null));
				}
			}
		}
		
		return RespVO.createSuccessJsonResonse(reqData);
	}
	
	
}